<template>
  <MainPage activeMenu="/login">
    <el-container>
      <el-main>
        <div class="login-container">
          <el-card class="login-card">
            <h2>登录</h2>
            <el-form ref="form" label-width="120px">
              <el-form-item label="用户名">
                <el-input v-model="username" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="密码">
                <el-input type="password" v-model="password" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleLogin" :loading="loading" style="width: 100%;">登录</el-button>
              </el-form-item>
              
              <el-form-item>
                <el-button type="text" @click="handleRegister" style="width: 100%; text-align: center;">注册</el-button>
              </el-form-item>
              
              <el-form-item v-if="message">
                <el-alert :title="message" :type="alertType" show-icon></el-alert>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </MainPage>
</template>

<script>
import MainPage from '../Component/MainPage.vue';
import axios from '../../axios/axios';

export default {
  components: {
    MainPage
  },
  data() {
    return {
      activeMenu: '/login',
      username: '',
      password: '',
      message: '',
      alertType: 'info', // 添加 alertType 用于控制消息的类型
      loading: false // 初始化 loading 状态
    }
  },
  methods: {
    async handleLogin() {
      if (!this.username || !this.password) {
        this.message = '用户名或密码不能为空';
        this.alertType = 'error'; // 设置消息类型为 error
        return;
      }

      this.loading = true; // 添加 loading 状态
      try {
        const response = await axios.post('/auth/doLogin', {
          username: this.username,
          password: this.password,
        }, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        // 假设 response.data 已经是解析后的数据
        this.message = response; // 使用 response，因为已经配置为直接使用 response.data

        // 判断是否登录成功
        if (response === '登录成功') {
          this.$router.push('/manage'); // 登录成功后跳转到 /manage
        } else {
          this.alertType = 'error'; // 设置消息类型为 error
        }

      } catch (error) {
        console.error('Login error:', error);
        this.message = (error.response) ? error.response : '登录请求失败';
        this.alertType = 'error'; // 设置消息类型为 error
      } finally {
        this.loading = false; // 恢复 loading 状态
      }
    },
    handleRegister() {
      this.$router.push('/register'); // 路由跳转到注册页面
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-card {
  width: 400px;
}
</style>
